package com.course.android.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.baselib.android.event.EventManager;
import com.baselib.android.utils.TimeUtils;
import com.course.android.NewApplication;
import com.course.android.R;
import com.course.event.EventBusKey;
import com.course.event.EventVo;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

public class DownLoadService  extends Service {


    public static String fileDir = "news";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private int progress;//当前进度
    private int lastRate = 0;
    private String apkUrl = "";
    private String saveFileName = fileDir + File.separator + "temp.apk";
    private String saveFileName1 = fileDir + File.separator + "temp.apk1";
    NotificationCompat.Builder notificationBuilder;

    @Override
    public void onCreate() {
        super.onCreate();
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        getNotificationBuilder();

        if (Build.VERSION.SDK_INT >= 26) {
            notificationBuilder = new NotificationCompat.Builder(NewApplication.getApp())
                    .setChannelId("100").setDefaults(Notification.DEFAULT_LIGHTS)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(getResources().getString(R.string.app_name) + "有新版本")
                    .setTicker("新版本正在下载中")
                    .setProgress(100, 0, true)
                    .setAutoCancel(false);
        } else {
            notificationBuilder = new NotificationCompat.Builder(NewApplication.getApp())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setDefaults(Notification.DEFAULT_LIGHTS)
                    .setContentTitle(getResources().getString(R.string.app_name) + "有新版本")
                    .setTicker("新版本正在下载中")
                    .setProgress(100, 0, true)
                    .setAutoCancel(false);
        }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            mNotificationManager.notify(0 /* ID of notification */,
                    notificationBuilder.build());
            apkUrl = intent.getStringExtra("url");
//            Log.e("xxxxx","xxxxx"+apkUrl);
            if (StringUtils.isNotBlank(apkUrl)) {
                if (!new File(Environment.getExternalStorageDirectory() + "/" + fileDir).exists()) {
                    new File(Environment.getExternalStorageDirectory() + "/" + fileDir).mkdirs();
                }
                saveFileName = Environment.getExternalStorageDirectory() + "/" + fileDir + File.separator  + TimeUtils.format_yyyyMMddHHmmss(new Date()) + ".apk";
                saveFileName1 = Environment.getExternalStorageDirectory() + "/" + fileDir + File.separator+ TimeUtils.format_yyyyMMddHHmmss(new Date()) + ".temp";
                progress = 0;//当前进度
                lastRate = 0;
                if (!new File(saveFileName).exists()) {
                    new DowLoadThread().start();
                } else {
                    install();
                }
            }
        } catch (Exception E) {
//            sendDownLoadFail();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    public void install() {
        try {


//            if (BaseApp.getInstance().getCurrentActName().contains("Version")) {
//                EventManager.getInstance().post(new DowLoadEvent(saveFileName));
//            } else {
//                install(BaseApp.getInstance().getApplicationContext(), saveFileName);
//            }
//            Log.e("xxxxx","xxxxx"+"install");

            EventVo eventVo = new EventVo(EventBusKey.APK_DOWNLOAD_INSTALL);
            eventVo.build(EventBusKey.APK_DOWNLOAD_INSTALL_KEY, saveFileName);
            EventManager.getInstance().post(eventVo);

        } catch (Exception e) {

        }
    }

    private class DowLoadThread extends Thread {
        @Override
        public void run() {
            super.run();
            try {
                URL url = new URL(apkUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();
                String apkFile = saveFileName1;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);
                int count = 0;
                byte buf[] = new byte[1024];
                while (true) {
                    int numread = is.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    // 更新进度
                    Message msg = mHandler.obtainMessage();
                    msg.what = 1;
                    msg.arg1 = progress;
                    if (progress >= lastRate + 1) {
                        if (progress % 2 == 1) {
                            mHandler.sendMessage(msg);
                            lastRate = progress;
                        }
                    }
                    if (numread <= 0) {
                        // 下载完成通知安装
                        mHandler.sendEmptyMessage(0);
                        // 下载完了，cancelled也要设置
                        break;
                    }
                    fos.write(buf, 0, numread);
                }
                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();


                sendDownLoadFail();
            } catch (IOException e) {
                e.printStackTrace();
                sendDownLoadFail();
            }

        }
    }


    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    // 下载完毕
                    // 取消通知
                    mNotificationManager.cancel(0);
                    sendDownLoadSuccess();
                    install();

                    break;
                case 1:
                    int rate = msg.arg1;
//                    Log.e("xxxxx","xxxxx");
                    if (rate < 100) {
                        notificationBuilder.setProgress(100, rate, true);
                        sendDownLoadDowning(rate);

                    } else {
                        sendDownLoadSuccess();
                    }
//                    mNotificationManager.notify(0 /* ID of notification */,
//                            notificationBuilder.build());
                    break;
            }
        }
    };

    private void sendDownLoadDowning(int vlaue) {
        EventVo eventVo = new EventVo(EventBusKey.APK_DOWNLOAD_RATE);
        eventVo.build(EventBusKey.APK_DOWNLOAD_RATE_VAL, vlaue);
        EventManager.getInstance().post(eventVo);
    }

    private void sendDownLoadSuccess() {
        try {
            File file = new File(saveFileName1);
            file.renameTo(new File(saveFileName));
        } catch (Exception e) {

        }
        EventVo eventVo = new EventVo(EventBusKey.APK_DOWNLOAD_OK);
        EventManager.getInstance().post(eventVo);
    }

    private void sendDownLoadFail() {
        try {
            File file = new File(saveFileName1);
            file.delete();
        } catch (Exception e) {

        }

        EventVo eventVo = new EventVo(EventBusKey.APK_DOWNLOAD_FAIL);
        EventManager.getInstance().post(eventVo);
    }


    private NotificationManager mNotificationManager;

// 通知栏

    private void getNotificationBuilder() {
        //大于8.0
        if (Build.VERSION.SDK_INT >= 26) {
            //id随便指定
            NotificationChannel channel = new NotificationChannel("100", getResources().getString(R.string.app_name) + "有新版本", NotificationManager.IMPORTANCE_DEFAULT);
            channel.canBypassDnd();//可否绕过，请勿打扰模式
            channel.enableLights(false);//闪光
            channel.canShowBadge();//桌面laucher消息角标
            channel.enableVibration(false);//是否允许震动
            channel.getGroup();//获取通知渠道组
            channel.setBypassDnd(true);//设置可以绕过，请勿打扰模式
            mNotificationManager.createNotificationChannel(channel);
        }

    }
}
